package com.xm.apd.nettyserver.netty;

import java.nio.ByteOrder;

import io.netty.buffer.ByteBuf;

/**
 * Created by XMclassmate on 2017/12/18.
 */

public class Message {

    private static final byte[] header = new byte[]{'X','M','c','l','a','s','s','m','a','t','e'};

    byte type; //1-客户端消息 2-服务端消息
    int size;
    byte[] bytes;

    public Message() {
    }

    public Message(byte type,int size, byte[] bytes) {
        this.type = type;
        this.size = size;
        this.bytes = bytes;
    }

    public void writeToBuf(ByteBuf buf){
        buf = buf.order(ByteOrder.LITTLE_ENDIAN);
        buf.writeBytes(header);
        buf.writeByte(type);
        buf.writeInt(bytes.length);
        buf.writeBytes(bytes);
    }

    public Message(ByteBuf frame){
        frame = frame.order(ByteOrder.LITTLE_ENDIAN);
        type = frame.readByte();
        size = frame.readInt();
        bytes = new byte[size];
        frame.readBytes(bytes);
    }

    public static boolean verifyHead(ByteBuf buf){
        for (int i = 0; i < header.length; i++) {
            byte temp = buf.readByte();
            if (temp != header[i])
                return false;
        }
        return true;
    }

    public byte getType() {
        return type;
    }

    public void setType(byte type) {
        this.type = type;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }
}
